﻿using System;

namespace Kaleida.ServiceMonitor.Model.Statistics
{
    public class AggregateDurationCalculator
    {
        private long? minimumTicks ;
        private long? maximumTicks ;
        private long? meanTicks ;
        private long? recentTicks ;
        private int count;

        public void AddResult(TimeSpan duration)
        {
            count++;
            if (meanTicks == null)
            {
                meanTicks = duration.Ticks;
            }
            else
            {
                long difference = duration.Ticks - meanTicks.Value;
                meanTicks += (difference / count);
            }

            if (minimumTicks == null || duration.Ticks < minimumTicks.Value)
            {
                minimumTicks = duration.Ticks;
            }

            if (maximumTicks == null || duration.Ticks > maximumTicks.Value)
            {
                maximumTicks = duration.Ticks;
            }

            recentTicks = duration.Ticks;
        }

        public TimeSpan? GetMean()
        {
            if (meanTicks == null)
                return null;

            return TimeSpan.FromTicks(meanTicks.Value);
        }

        public TimeSpan? GetMinimum()
        {
            return minimumTicks == null ? (TimeSpan?) null : TimeSpan.FromTicks(minimumTicks.Value);
        }

        public TimeSpan? GetMaximum()
        {
            return maximumTicks == null ? (TimeSpan?) null : TimeSpan.FromTicks(maximumTicks.Value);
        }

        public TimeSpan? GetMostRecent()
        {
            return recentTicks == null ? (TimeSpan?)null : TimeSpan.FromTicks(recentTicks.Value);
        }

        public void Reset()
        {
            meanTicks = null;
            minimumTicks = null;
            maximumTicks = null;
            recentTicks = null;
            count = 0;
        }
    }
}
